//
//  NewDeviceViewController.m
//  Demo
//
//  Created by Echo on 13-10-17.
//

#import "NewWifiViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "FirstTimeConfig.h"
//#import "PokerControlClient.h"
#import "PokerControlClient.h"
#import "DDAlertPrompt.h"
#import "DeviceListViewController.h"
#import "RecInfo.h"

@interface NewDeviceViewController (){
    NSTimer *timer;
}
@end

@implementation NewDeviceViewController
@synthesize wifissid,udpSocket;
@synthesize config, devname;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        [NC addObserver:self selector:@selector(stopUdpData) name:StopUdpData object:nil];
        [NC addObserver:self selector:@selector(getSocketData:) name:GET_SEARCH_SOCKET_UdpData object:nil];
        [NC addObserver:self selector:@selector(app_management:) name:NOTI_app_management_INFO object:nil];
        [NC addObserver:self selector:@selector(resignActive) name:NOTI_RESIGN_ACTIVE object:nil];
        [NC addObserver:self selector:@selector(becomeActive) name:NOTI_BECOME_ACTIVE object:nil];
    }
    return self;
}
-(void)app_management:(NSNotification*)noti{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    NSString *string = noti.object;
    NSRange range = [string rangeOfString:@"pwcheck=\""];
    NSString *nextstr = [string substringFromIndex:range.location+range.length];
    NSString *asdfas = [nextstr substringToIndex:1];
    if ([asdfas integerValue] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"密码错误，设备验证失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"密码正确，设备已经成功加入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        NSString *VALUE = [dicList objectForKey:self.devname];
        if (VALUE) {
            NSDictionary *oldList = [UD objectForKey:LANIPAddress_list];
            NSMutableDictionary *dicListww = nil;
            if (oldList) {
                dicListww = [[NSMutableDictionary alloc] initWithDictionary:oldList];
            }else{
                dicListww = [[NSMutableDictionary alloc] init];
            }
            [dicListww setObject:VALUE forKey:self.devname];
            [UD setObject:dicListww forKey:LANIPAddress_list];
            [UD synchronize];
            
            [dicList removeObjectForKey:self.devname];//for test
        }
    }
    
    [TableView1 reloadData];
}
-(void)dealloc{
    [NC removeObserver:self];
}
- (void)scan{
    int port = 15003;
    if (!self.udpSocket) {
        self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
        NSError *error = nil;
        [self.udpSocket enableBroadcast:YES error:&error];
        if (![self.udpSocket bindToPort:port error:&error])
        {
            NSLog(@"bindToPort error");
            return;
        }
    }
    [self.udpSocket receiveWithTimeout:-1 tag:0];
    NSString *sentip = @"255.255.255.255";
    NSString *dataStr = @"INFOSearchDevice030045000400040002000E0002";
    dataStr = send_str;
    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@" SEND TO : %@:%d    %@", sentip, port, dataStr);
    [self.udpSocket sendData:data toHost:sentip port:port withTimeout:-1 tag:0];
}

- (void)viewDidLoad
{
//    self.title = STR(@"添加新设备");
    if ([Global curLanguageEn]) {
        self.title = @"Add New Device";
    }
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"扫描" style:UIBarButtonItemStylePlain target:self action:@selector(scan)];
    
    dicList = [[NSMutableDictionary alloc] init];
    
    TableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-44-20) style:UITableViewStylePlain];
    TableView1.backgroundColor = [UIColor clearColor];
    TableView1.delegate = self;
    TableView1.dataSource = self;
    TableView1.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:TableView1];
}
- (void)getSocketData:(NSNotification*)noti{
    NSDictionary *dic = noti.object;
    NSDictionary *UDDIC = [UD objectForKey:LANIPAddress_list];
    if (dic.count > 0) {
        if ([UDDIC objectForKey:[[dic allKeys] objectAtIndex:0]]) {//for test
            NSLog(@"cunzai le ");
        }else{
            [dicList addEntriesFromDictionary:dic];
        }
    }
    [TableView1 reloadData];
}
-(void)stopUdpData{
    NSLog(@"停止发送udp包");
    isStopUdpData = YES;
    self.udpSocket = nil;
}
- (void)resignActive{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self stopUdpData];
}
- (void)becomeActive{
    [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:1];
    [self performSelector:@selector(tip) withObject:nil afterDelay:10];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopUdpData];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self sendUdpData];
    
    [self performSelector:@selector(tip) withObject:nil afterDelay:10];
}

-(void)tip{
    if (dicList.count == 0) {
        NSString *MSG = @"无新设备";
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:MSG delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
    }
}
-(void)sendUdpData{
    if (!isStopUdpData) {
        [self scan];
        [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:2];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dicList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}

-(unsigned int)getIntyy:(NSString*)nextstr{
    unsigned int tempf;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *str1 = [mutString substringFromIndex:4];
    NSString *str2 = [mutString substringToIndex:4];
    NSString *string1 = [NSString stringWithFormat:@"%@%@", str1, str2];
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt: &tempf];
    return tempf;
    //    label.text = [NSString stringWithFormat:@"%d.0", tempf];
}


-(float)getFloatyy:(NSString*)nextstr{
    unsigned tempi;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *str1 = [mutString substringFromIndex:4];
    NSString *str2 = [mutString substringToIndex:4];
    NSString *string1 = [NSString stringWithFormat:@"%@%@", str1, str2];
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt:&tempi];
    float *tempf = (float *)&tempi;
    return *tempf;
}

-(NSString* )getStringxxyy:(NSString*)nextstr{
    NSString *mutString = [nextstr substringFromIndex:2];
    return [RecInfo stringFromHexString:mutString];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"TableView1Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSString *name = [[dicList allKeys] objectAtIndex:indexPath.row];
    cell.imageView.image = nil;
    NSString *string = [name substringToIndex:1];
    if ([string integerValue] == 1) {
        cell.imageView.image = IMG(@"login_passwordIcon.png");
    }
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.text = [name substringFromIndex:1];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:17];
    cell.backgroundColor = [UIColor clearColor];
//    return cell;
    
//    
//    static NSString *CellIdentifier = @"TableView1Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    }
//    
//    UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, cell_height-2)];
//    bg.backgroundColor = [UIColor whiteColor];
//    [cell addSubview:bg];
//    
//    UIImageView *imageLock = [[UIImageView alloc] initWithImage:IMG(@"login_passwordIcon.png")];
//    imageLock.hidden = YES;
//    imageLock.frame = CGRectMake(10, cell_height/2-FH(imageLock)/2, FW(imageLock), FH(imageLock));
//    [bg addSubview:imageLock];
//    
//    NSString *name = [[dicList allKeys] objectAtIndex:indexPath.row];
//    cell.imageView.image = nil;
//    NSString *string = [name substringToIndex:1];
//    if ([string integerValue] == 1) {
//        imageLock.hidden = NO;
//        cell.imageView.image = IMG(@"login_passwordIcon.png");
//    }
//    cell.textLabel.textColor = [UIColor whiteColor];
////    cell.textLabel.text = [name substringFromIndex:1];
//    cell.textLabel.font = [UIFont systemFontOfSize:11];
//    cell.backgroundColor = [UIColor clearColor];
//    
//    
//    UIImageView *viewbg = [[UIImageView alloc] initWithFrame:CGRectMake(110, 8, SCREEN_WIDTH-110*2, cell_height-40)];
//    viewbg.backgroundColor = RGB(0, 105, 235, 1);
//    viewbg.layer.masksToBounds = YES;
//    viewbg.layer.cornerRadius = 10;
//    [cell addSubview:viewbg];
//    
//    UIImageView *logo = [[UIImageView alloc] initWithImage:IMG(@"control_logo.png")];
//    logo.frame = CGRectMake(1.5+8, 9.5, 66-8*2, 43);
//    [cell addSubview:logo];
//    logo.hidden = YES;
//    
//    GoodLabel *nameLabel = [GoodLabel labelWithFont:20 title:STR(@"")];
//    nameLabel.adjustsFontSizeToFitWidth = YES;
//    nameLabel.textAlignment = UITextAlignmentCenter;
//    nameLabel.textColor = [UIColor whiteColor];
//    nameLabel.frame = CGRectMake(0, 12, FW(viewbg), 20);
//    [viewbg addSubview:nameLabel];
//    
    NSString *device_name = nil;
    if ([dicList allKeys].count > indexPath.row) {
        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
//        GoodLabel *deviceLabel = [GoodLabel labelWithFont:17 title:[device_name substringFromIndex:1]];
//        deviceLabel.textAlignment = UITextAlignmentCenter;
//        deviceLabel.textColor = nameLabel.textColor;
//        deviceLabel.frame = CGRectMake(0, 30+5-FY(viewbg)-5+17, FW(viewbg), 20);
//        [viewbg addSubview:deviceLabel];
//        
        NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
//        NSString *UserDeviceName = [dicNameList objectForKey:device_name];
//        if ([UserDeviceName length] > 0) {
//            nameLabel.text = UserDeviceName;
//        }
        //版本  瞬时流量  累计量 046D332F68(瞬时流量的单位string) 087632353031313336(仪表序列号string) 0406513F9E(瞬时流量/秒real) 0406513F9E(瞬时流量/分real) 0406513F9E(瞬时流量/小时real) 0419330000(净累积量int) 020003(净累积量int)
        
        NSString *string = [[device_name substringFromIndex:1] substringFromIndex:2];
        NSString *num1 = [string substringToIndex:2];
        NSString *stringsub1 = [string substringToIndex:2+[num1 intValue]*2];
        NSString *getstring1 = [self getStringxxyy:stringsub1];//瞬时流量的单位string1
        
        string = [string substringFromIndex:2+[num1 intValue]*2];
        NSString *num2 = [string substringToIndex:2];
        NSString *stringsub2 = [string substringToIndex:2+[num2 intValue]*2];
        NSString *getstring2 = [self getStringxxyy:stringsub2];//仪表序列号string2
        
        cell.textLabel.text = getstring2;
        
//        string = [string substringFromIndex:2+[num2 intValue]*2];
//        NSString *num3 = [string substringToIndex:2];
//        NSString *stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
//        stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
//        float getfloat1 = [self getFloatyy:stringsub3];//瞬时流量/秒real3
//        
//        string = [string substringFromIndex:2+[num3 intValue]*2];
//        NSString *num4 = [string substringToIndex:2];
//        NSString *stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
//        stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
//        float getfloat2 = [self getFloatyy:stringsub4];//瞬时流量/秒real4
//        
//        string = [string substringFromIndex:2+[num4 intValue]*2];
//        NSString *num5 = [string substringToIndex:2];
//        NSString *stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
//        stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
//        float getfloat3 = [self getFloatyy:stringsub5];//瞬时流量/秒real5
//        
//        string = [string substringFromIndex:2+[num5 intValue]*2];
//        NSString *num6 = [string substringToIndex:2];
//        NSString *stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
//        stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
//        unsigned int getint1 = [self getIntyy:stringsub6];//净累积量int1
//        
//        string = [string substringFromIndex:2+[num6 intValue]*2];
//        NSString *num7 = [string substringToIndex:2];
//        NSString *stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
//        stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
////        unsigned int getint2 = [self getIntyy:stringsub7];//净累积量指数int2
//        
//        
//        GoodLabel *visionLabel = [GoodLabel labelWithFont:14 title:STR(@"")];
//        visionLabel.textAlignment = UITextAlignmentCenter;
//        visionLabel.textColor = viewbg.backgroundColor;
//        visionLabel.frame = CGRectMake(FX(viewbg), cell_height-30, FW(viewbg), 20);
//        [cell addSubview:visionLabel];
//        
//        visionLabel.text = getstring2;
//        if ([getstring1 hasSuffix:@"s"]) {
//            deviceLabel.text = [NSString stringWithFormat:@"%.2f (%@)", getfloat1, getstring1];//瞬时流量
//        }else if ([getstring1 hasSuffix:@"m"]) {
//            deviceLabel.text = [NSString stringWithFormat:@"%.2f (%@)", getfloat2, getstring1];//瞬时流量
//        }else{
//            deviceLabel.text = [NSString stringWithFormat:@"%.2f (%@)", getfloat3, getstring1];//瞬时流量
//        }
//        
//        nameLabel.text = [NSString stringWithFormat:@"%d×%@", getint1, [RecInfo getInt:stringsub7]];
        
//        label.text = [NSString stringWithFormat:@"%d×%d", getint1, [self getIntxx:nextstr]];
        
    }
//
    return cell;
}
-(unsigned int )getIntxx:(NSString*)nextstr{
    unsigned int tempf;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *string1 = mutString;
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt: &tempf];
    int zhishu = 1;
    for (int i=0;i<tempf;i++) {
        zhishu = 10*zhishu;
    }
    return zhishu;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *name = [[dicList allKeys] objectAtIndex:indexPath.row];
    NSString *savaIP = [[dicList allValues] objectAtIndex:indexPath.row];
    NSString *string = [name substringToIndex:1];
    
    self.devname = name;
    
    if ([string integerValue] == 1) {
        
        DDAlertPrompt *loginPrompt = nil;
        
            loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"请输入设备密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitle:@"确定" content:@""];
            loginPrompt.tag = 23;
            [loginPrompt show];
        [PokerControlClient share].ctrlIP = savaIP;
        NSLog(@"需要密码");
        [self stopUdpData];
    }else{
        
        NSString *VALUE = [dicList objectForKey:self.devname];
        if (VALUE) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备已经成功加入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            NSDictionary *oldList = [UD objectForKey:LANIPAddress_list];
            NSMutableDictionary *dicListww = nil;
            if (oldList) {
                dicListww = [[NSMutableDictionary alloc] initWithDictionary:oldList];
            }else{
                dicListww = [[NSMutableDictionary alloc] init];
            }
            [dicListww setObject:VALUE forKey:self.devname];
            [UD setObject:dicListww forKey:LANIPAddress_list];
            [UD synchronize];
            
            [dicList removeObjectForKey:self.devname];
            [TableView1 reloadData];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        DDAlertPrompt *loginPrompt = (DDAlertPrompt *)alertView;
        NSString *groupName = loginPrompt.plainTextField.text;
        if ([groupName length] > 0) {
            NSString *string = [NSString stringWithFormat:@"<app_data password=\"%@\"/>", groupName];
            [[PokerControlClient share] startCmd:@"5" code:string];
        }
    }
}
- (void)sendData{
    
}

@end








